<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use App\Helpers\Helper;
use App\Helpers\RedisUtil;
use App\Model\UserMsgLog;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Server\ServerFactory;
use PhpAmqpLib\Message\AMQPMessage;

/**
 * @Consumer(exchange="hyperf", routingKey="hyperf", queue="hyperf", name ="ImMsgConsumer", nums=1)
 */
class ImMsgConsumer extends ConsumerMessage
{
    /**
     * rabbmitMQ消费端代码
     * @param $data
     * @return string
     */
    public function consume($data): string
    {
        // var_dump($data);

        //获取集合中所有的value
        // $redis = $this->container->get(\Redis::class);
        $redis = RedisUtil::getRedis();
        $fdList = $redis->sMembers(RedisUtil::WS_CLIENT_FD_KEY);
        $server = $this->container->get(ServerFactory::class)->getServer()->getServer();
        log_info(__CLASS__ . "=={$data}");
        $message = \json_decode($data, true);
        $key = Helper::getListKey([$message['from_account'], $message['to_account']]);
        $chatDetail = \json_decode($message['msg_detail'], true);
        $msg['type'] = 'new_msg';
        $msg['content'][$key] = [
            'send' => $message['send'],
            'detail' => UserMsgLog::packMsgDetail($chatDetail, $message['msgUID']),
            'msg_time' => $message['msg_time'],
            'from_userid' => $message['from_userid'],
            'to_userid' => $message['to_userid']
        ];
        foreach ($fdList as $key => $v) {
            if (!empty($v)) {
                $server->push((int)$v, \json_encode($msg));
            }
        }
        return Result::ACK;
    }
}
